<template>
  <tm-app>
    <!-- 顶部导航 -->

    <tm-navbar title="" linear="right" :hideHome="true" color="orange">
      <template v-slot>分类</template>
      <!-- <template v-slot> -->
      <!-- <tm-input
          class="search-input"
          v-model="text"
          placeholder="请输入"
          :searchWidth="120"
          @confirm="search"
          suffix="tmicon-search"
        ></tm-input> -->
      <!-- <tm-input
          class="search-input"
          :searchWidth="120"
          @search="search"
          prefix="tmicon-search"
          searchLabel="搜索"
        ></tm-input> -->
      <!-- </template> -->
    </tm-navbar>
    <tm-sheet class="flex flex-row flex-1" :margin="[0, 0]" :padding="[0, 0]">
      <!-- 左侧分类 -->
      <scroll-view
        :scroll-top="scrollTop"
        scroll-y
        scroll-with-animation
        class="shop-sv menu-scroll-view"
        style="width: 200rpx"
      >
        <view
          class="shop-tab-item"
          v-for="(item, index) in cateList"
          :key="item.id"
          @tap.stop="swichMenu(index, item.id)"
          :class="[categoryIndex === index && 'shop-tab-item-active']"
          _class="flex flex-row flex-row-center-start"
        >
          <tm-text :font-size="24" :padding="[10, 10]" :color="categoryIndex === index ? 'orange' : undefined">
            {{ item.name }}
          </tm-text>
          <tm-icon
            :fontSize="20"
            name="tmicon-md-more"
            :color="categoryIndex === index ? 'orange' : undefined"
          ></tm-icon>
        </view>
      </scroll-view>
      <!-- 右侧列表 -->
      <view class="shop-sv" style="background-color: #fff; width: 522rpx; padding: 0rpx 30rpx 0 0">
        <tm-virtual-list
          v-if="skuProductList.length > 0"
          :scroll-view-in-to="test"
          :first-load="false"
          :load="getdata"
          :width="626"
          :height="1052"
          color="white"
          :data="skuProductList"
          :itemHeight="200"
        >
          <template v-slot:default="{ data }">
            <tm-sheet
              borderDirection="bottom"
              :height="200"
              :width="200"
              :padding="[10, 10]"
              :margin="[10, 10]"
              v-for="(item, index) in data.slice(0, len)"
              :key="index"
            >
              <view
                class="flex flex-row flex-row-center-around flex-1"
                style="width: 270px; padding: 10px; box-sizing: border-box; margin-top: 10px"
              >
                <ListImgItem
                  :src="item.imgUrl"
                  :width="180"
                  :height="180"
                  :showLeft="productTipChecker(item, 'left')"
                  :showBottom="productTipChecker(item, 'bottom')"
                ></ListImgItem>
                <view class="right-box" @click="toDetail(item)">
                  <tm-text :font-size="28" :label="item.skuName"></tm-text>
                  <tm-text :font-size="20" color="rgb(141 146 152)">
                    已售{{ item.sale }} /剩余{{ item.stock - item.sale }}
                  </tm-text>
                  <view v-if="item.ruleList">
                    <tm-text v-for="(elem, index) in item.ruleList" :key="index" :font-size="24" color="red">
                      {{ elem }}
                    </tm-text>
                  </view>
                  <view class="price-btn flex flex-row flex-row-around flex-1" style="width: 280rpx">
                    <tm-text :font-size="28" color="orange">￥{{ item.price.toFixed(2) }}</tm-text>

                    <AddToCart :skuId="item._id" :perLimit="item.perLimit"></AddToCart>
                  </view>
                </view>
                <tm-divider color="green"></tm-divider>
              </view>
            </tm-sheet>
            <view class="flex flex-row flex-row-center-center">
              <tm-text v-if="last">---我是有底线的---</tm-text>
            </view>
          </template>
        </tm-virtual-list>
        <tm-result
          :size="120"
          v-if="skuProductList.length <= 0"
          title="商品上新中"
          subTitle="敬请期待"
          icon="tmicon-map-fill"
          :showBtn="false"
        ></tm-result>
      </view>
    </tm-sheet>
  </tm-app>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { onReady } from '@dcloudio/uni-app'
import tmApp from '@/tmui/components/tm-app/tm-app.vue'
import tmNavbar from '@/tmui/components/tm-navbar/tm-navbar.vue'
// import tmInput from "@/tmui/components/tm-input/tm-input.vue"
import tmText from '@/tmui/components/tm-text/tm-text.vue'
import tmResult from '@/tmui/components/tm-result/tm-result.vue'
import tmVirtualList from '@/tmui/components/tm-virtual-list/tm-virtual-list.vue'
import { nextTick, getCurrentInstance } from 'vue'
import tmDivider from '@/tmui/components/tm-divider/tm-divider.vue'
// pinia
import { useCateStore, useIndexStore } from '@/store'
const { setProductDetails, setSkuId } = useIndexStore()
const { categoryId, categoryIndex } = storeToRefs(useIndexStore())
const { setCateList, setSkuProductList } = useCateStore()
const { cateList, skuProductList } = storeToRefs(useCateStore())
// 引入接口
import { getProduct, getCategories, isLogin } from '@/api'
import type { SeckillSkuVo, HotSku } from '@/types'
// 是否显示新人专享
import { productTipChecker } from '@/utils/helper'
import { storeToRefs } from 'pinia'
import PubSub from 'pubsub-js'

const instance = getCurrentInstance() // 获取组件实例

interface IMenuHeight {
  // 菜单/菜单项数据类型约束
  [key: string]: number
}
const menuHeightObj: IMenuHeight = {}
let scrollTop = ref<number>(0) // 左侧分类栏滚动位置
let menuHeight = ref<number>(0) // 左边菜单的高度
let menuItemHeight = ref<number>(0) // 左边菜单item的高度

// 搜索
// const text = ref("")
// function search(val: string) {
//   console.log(val)
// }

// 切换菜单
const swichMenu = async (index: number, id: number) => {
  if (index == current.value) return
  await nextTick()
  categoryIndex.value = index
  last.value = false
  len.value = 5
  current.value = index // 当前索引的值
  active.value = id // 分类id的值
  await leftMenuStatus(index) // 左侧菜单滚动到指定位置
  getSkuProductList() // 获取商品列表
}

// 计算高亮颜色
const setActiveColor = (index: number) => {
  current.value === index ? 'orange' : undefined
  categoryIndex.value = index
}

// 左侧分类列表
// 类别id
const active = ref(0)
const current = ref(0)
const getCateList = async () => {
  const res = await getCategories()
  setCateList(res.data)
}

// 右侧商品列表
// 商品列表展示数量
type Positions = '' | 'bottom' | 'top' | undefined
const len = ref(5)
const last = ref(false)
const test = ref<Positions>('')
const getSkuProductList = async () => {
  const res = await getProduct(active.value)
  await nextTick()
  setSkuProductList(res.data)
}

// 获取一个目标元素的高度
async function getElRect(elClass: any, dataVal: any) {
  return new Promise((resolve) => {
    // 获取节点信息
    const query = uni.createSelectorQuery().in(instance)
    query
      .select('.' + elClass)
      .fields(
        {
          size: true,
        },
        (res) => {
          // 如果节点尚未生成，res值为null，循环调用执行
          if (!res) {
            setTimeout(() => {
              getElRect(elClass, dataVal)
            }, 10)
            return
          }
          // 高度值的返回
          const height = res.height !== undefined ? res.height : 0
          menuHeightObj[dataVal] = height
          resolve(res.height)
        },
      )
      .exec()
  })
}

// 左侧菜单滚动到指定位置
const leftMenuStatus = async (index: number) => {
  current.value = index // 重置当前项的值
  // 获取菜单的高度位置
  if (menuHeight.value === 0 || menuItemHeight.value === 0) {
    await getElRect('menu-scroll-view', 'menuHeight')
    await getElRect('shop-tab-item', 'menuItemHeight')
  }
  await nextTick() //
  // 获取菜单的高度位置
  menuHeight.value = menuHeightObj.menuHeight
  menuItemHeight.value = menuHeightObj.menuItemHeight

  // 计算滚动顶点位置
  scrollTop.value = index * menuItemHeight.value + menuItemHeight.value / 2 - menuHeight.value / 2
}

// 上拉、下拉虚拟列表
const getdata = (e: string) => {
  if (last.value) {
    return true
  }
  return new Promise((res) => {
    setTimeout(function () {
      if (!last.value) {
        if (e == 'top') {
          console.log('top')
        } else if (e == 'bottom') {
          if (len.value < skuProductList.value.length) {
            len.value += 3
          } else {
            last.value = true
          }
        }
      }
      res(true)
    }, 1000)
  })
}

// // 跳转详情
const toDetail = (data: HotSku | SeckillSkuVo) => {
  setProductDetails(data as HotSku)
  setSkuId(data._id)
  uni.navigateTo({
    url: '/pages/homeItem/homeItem',
  })
}

PubSub.subscribe('categoryChange', (msg, data) => {
  console.log(msg)
  console.log('收到分类数据更新通知:', data)
  // updateCategoryList(data)
})

onReady(() => {
  // 请求数据
  uni.showLoading({
    title: '加载中',
  })
  setTimeout(() => {
    uni.hideLoading()
  }, 500)
})
onMounted(async () => {
  // 判断是否登录
  const result = isLogin()
  if (!result) {
    uni.redirectTo({
      url: '/pages/login/index',
    })
  } else {
    getCateList()
    getSkuProductList()
    if (categoryId && categoryIndex) {
      swichMenu(categoryIndex.value, categoryId.value)
      setActiveColor(categoryIndex.value)
      await leftMenuStatus(categoryIndex.value)
    }
    // 订阅从首页来的通知
    PubSub.subscribe('gotoCategory', async () => {
      await leftMenuStatus(categoryIndex.value)
    })
  }
})
</script>

<style lang="scss" scoped>
.search-input {
  width: 600rpx;
}

.right-box {
  margin: 0px 30px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;

  // 按钮
  .price-btn {
    display: flex;
    justify-content: space-between;
    margin-top: 30rpx;
    width: 300rpx;
    align-items: center;
  }
}

.shop-sv {
  height: calc(100vh - 78px);
}

.shop-tab-item {
  height: 110rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tm-sheet {
  display: flex !important;
}

.shop-tab-item-active {
  font-weight: bold;
  position: relative;
  background-image: linear-gradient(to left, rgba(255, 255, 255, 0.3), rgba(211, 186, 186, 0.3));
  border-left: 2px solid orange;
}
</style>
